package com.getpebble.android.common.model;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ObjectUtil;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.model.PblDataModel.Column;
import com.getpebble.android.common.model.PblDataModel.Column.Type;
import com.getpebble.android.util.SQLUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.UnsignedInteger;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.ArrayList;
import java.util.List;

public class PblDeviceModel extends PblDataModel {
    public static final String[] ALL_FIELDS_PROJECTION = new String[]{"_id", "friendly_name", "address", "serial_number", "hw_revision", "fw_version", "fw_timestamp", "hw_platform", "recovery_fw_version", "is_recovery", "capabilities", "connection_status", "last_connected_time", "current_running_app", "color", "connection_goal", "rssi", "iso_locale", "language_version"};
    private static final String[] ARGS_CONNECTION_GOAL_CONNECT = new String[]{String.valueOf(ConnectionGoal.CONNECT.getIntValue())};
    private static final String[] ARGS_CONNECTION_STATUS_CONNECTED = new String[]{String.valueOf(ConnectionStatus.CONNECTED.getIntValue())};
    public static int ERROR_NULL_CONTENT_RESOLVER = -1;
    public static int ERROR_NULL_CONTENT_VALUES = -3;
    public static int ERROR_NULL_PBL_DEVICE = -2;
    public static final Uri TABLE_URI = PblContentProviderUtil.getTableUri("devices");
    private static final String TAG = PblDeviceModel.class.getSimpleName();

    static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$common$model$PblDeviceModel$Query = new int[Query.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$common$model$PblDeviceModel$Query[Query.CONNECTION_GOAL_CONNECT.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PblDeviceModel$Query[Query.CONNECTION_STATUS_CONNECTED.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PblDeviceModel$Query[Query.LAST_CONNECTED.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
        }
    }

    public static class PblDeviceRecord {
        public final PebbleColor color;
        public final ConnectionGoal connectionGoal;
        public final ConnectionStatus connectionStatus;
        public final FirmwareVersion fwVersion;
        public final HardwarePlatform hwPlatform;
        public final String hwRevision;
        public final boolean isRunningRecoveryFw;
        public final String isoLocale;
        public final int languageVersion;
        public final long lastConnectedTimeMillis;
        public final PblDevice pblDevice;
        public final FirmwareVersion recoveryFwVersion;
        public final String serialNumber;

        public PblDeviceRecord(PblDevice pblDevice, String serialNumber, String hwRevision, FirmwareVersion fwVersion, HardwarePlatform hwPlatform, FirmwareVersion recoveryFwVersion, boolean isRunningRecoveryFw, ConnectionStatus connectionStatus, long lastConnectedTimeMillis, PebbleColor color, ConnectionGoal connectionGoal, String isoLocale, int languageVersion) {
            this.pblDevice = pblDevice;
            this.serialNumber = serialNumber;
            this.hwRevision = hwRevision;
            this.fwVersion = fwVersion;
            this.hwPlatform = hwPlatform;
            this.recoveryFwVersion = recoveryFwVersion;
            this.isRunningRecoveryFw = isRunningRecoveryFw;
            this.connectionStatus = connectionStatus;
            this.lastConnectedTimeMillis = lastConnectedTimeMillis;
            this.color = color;
            this.connectionGoal = connectionGoal;
            this.isoLocale = isoLocale;
            this.languageVersion = languageVersion;
        }

        public static PblDeviceRecord getEmptyRecord() {
            return new PblDeviceRecord(null, null, null, null, null, null, false, null, 0, null, null, null, 0);
        }

        public boolean isEmpty() {
            return ObjectUtil.nullCheckEquals(this, getEmptyRecord());
        }

        public boolean equals(Object o) {
            if (o == null) {
                return false;
            }
            if (o == this) {
                return true;
            }
            if (o instanceof PblDeviceRecord) {
                return ObjectUtil.nullCheckEquals(this.pblDevice, ((PblDeviceRecord) o).pblDevice);
            }
            return false;
        }

        public int hashCode() {
            return this.pblDevice.hashCode() + 355;
        }
    }

    public enum Query {
        CONNECTION_GOAL_CONNECT,
        CONNECTION_STATUS_CONNECTED,
        LAST_CONNECTED
    }

    public PblDeviceModel() throws IllegalArgumentException {
        super("devices");
        addColumn(new Column(Type.STRING, "friendly_name"));
        Column addressColumn = new Column(Type.STRING, "address");
        addressColumn.setUnique(true);
        addColumn(addressColumn);
        addColumn(new Column(Type.STRING, "hw_revision"));
        addColumn(new Column(Type.STRING, "fw_version"));
        addColumn(new Column(Type.TIMESTAMP, "fw_timestamp"));
        addColumn(new Column(Type.INTEGER, "hw_platform"));
        addColumn(new Column(Type.STRING, "serial_number"));
        addColumn(new Column(Type.STRING, "recovery_fw_version"));
        addColumn(new Column(Type.STRING, "capabilities"));
        addColumn(new Column(Type.INTEGER, "is_recovery"));
        addColumn(new Column(Type.INTEGER, "connection_status"));
        addColumn(new Column(Type.TIMESTAMP, "last_connected_time"));
        addColumn(new Column(Type.STRING, "current_running_app"));
        addColumn(new Column(Type.INTEGER, "color"));
        addColumn(new Column(Type.INTEGER, "connection_goal"));
        addColumn(new Column(Type.INTEGER, "rssi"));
        addColumn(new Column(Type.STRING, "iso_locale"));
        addColumn(new Column(Type.INTEGER, "language_version"));
    }

    public static synchronized boolean insert(ContentResolver contentResolver, PblDevice device) {
        boolean insertDevice;
        synchronized (PblDeviceModel.class) {
            insertDevice = insertDevice(contentResolver, device, null);
        }
        return insertDevice;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static synchronized boolean insertDevice(android.content.ContentResolver r6, com.getpebble.android.common.model.PblDevice r7, android.content.ContentValues r8) {
        /*
        r2 = 0;
        r3 = com.getpebble.android.common.model.PblDeviceModel.class;
        monitor-enter(r3);
        if (r6 != 0) goto L_0x000f;
    L_0x0006:
        r4 = TAG;	 Catch:{ all -> 0x0019 }
        r5 = "Cannot insert device with null contentresolver";
        com.getpebble.android.common.core.trace.Trace.error(r4, r5);	 Catch:{ all -> 0x0019 }
    L_0x000d:
        monitor-exit(r3);
        return r2;
    L_0x000f:
        if (r7 != 0) goto L_0x001c;
    L_0x0011:
        r4 = TAG;	 Catch:{ all -> 0x0019 }
        r5 = "Cannot insert null device";
        com.getpebble.android.common.core.trace.Trace.warning(r4, r5);	 Catch:{ all -> 0x0019 }
        goto L_0x000d;
    L_0x0019:
        r2 = move-exception;
    L_0x001a:
        monitor-exit(r3);
        throw r2;
    L_0x001c:
        r4 = r7.getAddress();	 Catch:{ all -> 0x0019 }
        if (r4 != 0) goto L_0x002a;
    L_0x0022:
        r4 = TAG;	 Catch:{ all -> 0x0019 }
        r5 = "Cannot insert device with null address";
        com.getpebble.android.common.core.trace.Trace.warning(r4, r5);	 Catch:{ all -> 0x0019 }
        goto L_0x000d;
    L_0x002a:
        r1 = getCursorForDevice(r6, r7);	 Catch:{ all -> 0x0019 }
        if (r1 != 0) goto L_0x0038;
    L_0x0030:
        r4 = TAG;	 Catch:{ all -> 0x0019 }
        r5 = "Null cursor";
        com.getpebble.android.common.core.trace.Trace.warning(r4, r5);	 Catch:{ all -> 0x0019 }
        goto L_0x000d;
    L_0x0038:
        r1.moveToFirst();	 Catch:{ all -> 0x0019 }
        r4 = r1.getCount();	 Catch:{ all -> 0x0019 }
        if (r4 <= 0) goto L_0x004c;
    L_0x0041:
        r4 = TAG;	 Catch:{ all -> 0x0019 }
        r5 = "Record already exists; dropping insert request";
        com.getpebble.android.common.core.trace.Trace.debug(r4, r5);	 Catch:{ all -> 0x0019 }
        r1.close();	 Catch:{ all -> 0x0019 }
        goto L_0x000d;
    L_0x004c:
        if (r8 != 0) goto L_0x0074;
    L_0x004e:
        r0 = new android.content.ContentValues;	 Catch:{ all -> 0x0019 }
        r2 = 2;
        r0.<init>(r2);	 Catch:{ all -> 0x0019 }
        r2 = "friendly_name";
        r4 = r7.getName();	 Catch:{ all -> 0x007e }
        r0.put(r2, r4);	 Catch:{ all -> 0x007e }
        r2 = "address";
        r4 = r7.getAddress();	 Catch:{ all -> 0x007e }
        r0.put(r2, r4);	 Catch:{ all -> 0x007e }
        r2 = "rssi";
        r4 = r7.getRSSI();	 Catch:{ all -> 0x007e }
        r4 = java.lang.Short.valueOf(r4);	 Catch:{ all -> 0x007e }
        r0.put(r2, r4);	 Catch:{ all -> 0x007e }
        r8 = r0;
    L_0x0074:
        r2 = TABLE_URI;	 Catch:{ all -> 0x0019 }
        r6.insert(r2, r8);	 Catch:{ all -> 0x0019 }
        r1.close();	 Catch:{ all -> 0x0019 }
        r2 = 1;
        goto L_0x000d;
    L_0x007e:
        r2 = move-exception;
        r8 = r0;
        goto L_0x001a;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.common.model.PblDeviceModel.insertDevice(android.content.ContentResolver, com.getpebble.android.common.model.PblDevice, android.content.ContentValues):boolean");
    }

    public static synchronized int purgeUnknownDevices(ContentResolver contentResolver) {
        int i;
        synchronized (PblDeviceModel.class) {
            if (contentResolver == null) {
                Trace.error(TAG, "Cannot purge devices with null contentresolver");
                i = ERROR_NULL_CONTENT_RESOLVER;
            } else {
                String selectionClause = "last_connected_time is NULL";
                i = contentResolver.delete(TABLE_URI, "last_connected_time is NULL", null);
                Trace.debug(TAG, "Removed " + i + " unknown devices");
            }
        }
        return i;
    }

    public static synchronized boolean setAllDevicesDisconnected(ContentResolver contentResolver) {
        boolean z = true;
        synchronized (PblDeviceModel.class) {
            if (contentResolver == null) {
                Trace.error(TAG, "Cannot mark devices disconnected with null contentresolver");
                z = false;
            } else {
                ContentValues contentValues = new ContentValues(1);
                contentValues.put("connection_status", Integer.valueOf(ConnectionStatus.DISCONNECTED.getIntValue()));
                contentResolver.update(TABLE_URI, contentValues, null, null);
            }
        }
        return z;
    }

    public static synchronized int updateDevice(ContentResolver contentResolver, PblDevice device, ContentValues contentValues) {
        int i;
        synchronized (PblDeviceModel.class) {
            if (contentResolver == null) {
                Trace.error(TAG, "Cannot update device with null contentresolver");
                i = ERROR_NULL_CONTENT_RESOLVER;
            } else if (device == null) {
                Trace.warning(TAG, "Cannot update a null device");
                i = ERROR_NULL_PBL_DEVICE;
            } else if (device.getAddress() == null) {
                Trace.warning(TAG, "Cannot update device with null address");
                i = ERROR_NULL_CONTENT_VALUES;
            } else {
                String selectionClause = "address = ?";
                i = contentResolver.update(TABLE_URI, contentValues, "address = ?", new String[]{device.getAddress()});
                if (i == 1) {
                    Trace.debug(TAG, String.format("Updated device <%s>", new Object[]{device}));
                } else {
                    Trace.error(TAG, String.format("Updated %d rows, should have updated 1; device <%s>", new Object[]{Integer.valueOf(i), device}));
                }
            }
        }
        return i;
    }

    public static synchronized boolean updateOrInsertDevice(ContentResolver contentResolver, PblDevice device, ContentValues contentValues) {
        boolean z = true;
        boolean z2 = false;
        synchronized (PblDeviceModel.class) {
            Cursor cursor = getCursorForDevice(contentResolver, device);
            if (cursor == null) {
                Trace.warning(TAG, "Null cursor");
            } else {
                boolean shouldUpdateExistingDevice;
                cursor.moveToFirst();
                if (cursor.getCount() > 0) {
                    shouldUpdateExistingDevice = true;
                } else {
                    shouldUpdateExistingDevice = false;
                }
                cursor.close();
                if (shouldUpdateExistingDevice) {
                    if (updateDevice(contentResolver, device, contentValues) <= 0) {
                        z = false;
                    }
                    z2 = z;
                } else {
                    z2 = insertDevice(contentResolver, device, contentValues);
                }
            }
        }
        return z2;
    }

    public static synchronized PblDeviceRecord getPblDeviceRecordFromCursor(Cursor cursor) {
        PblDeviceRecord pblDeviceRecord;
        synchronized (PblDeviceModel.class) {
            try {
                FirmwareVersion fwVersion;
                FirmwareVersion recoveryFwVersion;
                boolean z;
                String name = cursor.getString(cursor.getColumnIndex("friendly_name"));
                String address = cursor.getString(cursor.getColumnIndex("address"));
                short rssi = cursor.getShort(cursor.getColumnIndex("rssi"));
                String fwString = cursor.getString(cursor.getColumnIndex("fw_version"));
                long fwTimeStamp = cursor.getLong(cursor.getColumnIndex("fw_timestamp"));
                if (TextUtils.isEmpty(fwString)) {
                    fwVersion = null;
                } else {
                    fwVersion = new FirmwareVersion(fwString, fwTimeStamp);
                }
                String recoveryFwString = cursor.getString(cursor.getColumnIndex("recovery_fw_version"));
                if (TextUtils.isEmpty(recoveryFwString)) {
                    recoveryFwVersion = null;
                } else {
                    recoveryFwVersion = new FirmwareVersion(recoveryFwString, 0);
                }
                String isoLocale = cursor.getString(cursor.getColumnIndex("iso_locale"));
                int languageVersion = cursor.getInt(cursor.getColumnIndex("language_version"));
                PblDevice pblDevice = new PblDevice(name, address, rssi);
                String string = cursor.getString(cursor.getColumnIndex("serial_number"));
                String string2 = cursor.getString(cursor.getColumnIndex("hw_revision"));
                HardwarePlatform fromInt = HardwarePlatform.fromInt(UnsignedInteger.valueOf((long) cursor.getInt(cursor.getColumnIndex("hw_platform"))));
                if (cursor.getInt(cursor.getColumnIndex("is_recovery")) != 0) {
                    z = true;
                } else {
                    z = false;
                }
                pblDeviceRecord = new PblDeviceRecord(pblDevice, string, string2, fwVersion, fromInt, recoveryFwVersion, z, ConnectionStatus.fromInt(cursor.getInt(cursor.getColumnIndex("connection_status"))), cursor.getLong(cursor.getColumnIndex("last_connected_time")), PebbleColor.fromInt(cursor.getInt(cursor.getColumnIndex("color"))), ConnectionGoal.fromInt(cursor.getInt(cursor.getColumnIndex("connection_goal"))), isoLocale, languageVersion);
            } catch (Throwable e) {
                Trace.error(TAG, "Error loading PblDeviceRecord from cursor", e);
                pblDeviceRecord = null;
            }
        }
        return pblDeviceRecord;
    }

    public static synchronized PblDeviceRecord getPblDeviceRecord(ContentResolver resolver, PblDevice device) {
        PblDeviceRecord record;
        synchronized (PblDeviceModel.class) {
            record = null;
            Cursor cursor = getCursorForDevice(resolver, device);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    record = getPblDeviceRecordFromCursor(cursor);
                }
                cursor.close();
            }
        }
        return record;
    }

    public static synchronized List<PblDeviceRecord> getPblDeviceRecords(ContentResolver resolver, Query query) {
        List<PblDeviceRecord> list;
        synchronized (PblDeviceModel.class) {
            list = new ArrayList();
            Cursor cursor = getCursorForDevices(resolver, query);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    PblDeviceRecord record = getPblDeviceRecordFromCursor(cursor);
                    if (record != null) {
                        list.add(record);
                    }
                }
                cursor.close();
            }
        }
        return list;
    }

    private static synchronized Cursor getCursorForDevice(ContentResolver contentResolver, PblDevice device) {
        Cursor query;
        synchronized (PblDeviceModel.class) {
            String selectionClause = "address = ?";
            ContentResolver contentResolver2 = contentResolver;
            query = contentResolver2.query(TABLE_URI, ALL_FIELDS_PROJECTION, "address = ?", new String[]{device.getAddress()}, null);
        }
        return query;
    }

    private static synchronized Cursor getCursorForDevices(ContentResolver contentResolver, Query query) {
        Cursor query2;
        synchronized (PblDeviceModel.class) {
            String selectionClause = null;
            String[] selectionArgs = null;
            String sort = null;
            switch (AnonymousClass1.$SwitchMap$com$getpebble$android$common$model$PblDeviceModel$Query[query.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    selectionClause = "connection_goal = ?";
                    selectionArgs = ARGS_CONNECTION_GOAL_CONNECT;
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    selectionClause = "connection_status = ?";
                    selectionArgs = ARGS_CONNECTION_STATUS_CONNECTED;
                    sort = "last_connected_time DESC";
                    break;
                case ListInfo.INDETERMINATE /*3*/:
                    selectionClause = "last_connected_time is NOT NULL";
                    sort = "last_connected_time DESC";
                    break;
            }
            query2 = contentResolver.query(TABLE_URI, ALL_FIELDS_PROJECTION, selectionClause, selectionArgs, sort);
        }
        return query2;
    }

    public static List<String> addLanguageColumnsCommands() {
        return ImmutableList.of(SQLUtil.getAddColumnCommand("devices", new Column(Type.STRING, "iso_locale")), SQLUtil.getAddColumnCommand("devices", new Column(Type.INTEGER, "language_version")));
    }

    public static int updateLanguageInfo(ContentResolver contentResolver, PblDevice device, String isoLocale, int version) {
        ContentValues contentValues = new ContentValues(2);
        contentValues.put("iso_locale", isoLocale);
        contentValues.put("language_version", Integer.valueOf(version));
        return updateDevice(contentResolver, device, contentValues);
    }
}
